//
//  ClarityBottomView.m
//  YouinRTCDemo
//
//  Created by 潘欣 on 2025/7/13.
//

#import "ClarityBottomView.h"
#import <LSTPopView/LSTPopView.h>

@interface ClarityBottomView ()
@property (nonatomic,weak) LSTPopView *popView;
@property(nonatomic,strong)UISegmentedControl *segmentedControl;
@property(nonatomic,strong)UILabel *clarityLabel;
@property(nonatomic,strong)UIButton *closeButton;
@property(nonatomic,strong)UILabel *bitrateLabel;//码率
@property(nonatomic,strong)UISlider *bitrateSlider;
@property(nonatomic,strong)UILabel *sliderValueLabel;
@property(nonatomic,strong)UIImageView *sliderImage;
@property(nonatomic,assign)float index;
@end

@implementation ClarityBottomView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        
        self.backgroundColor = [UIColor whiteColor];
        
        self.clarityLabel = [[UILabel alloc] init];
        self.clarityLabel.text = @"清晰度";
        self.clarityLabel.font = [UIFont systemFontOfSize:16];
        self.clarityLabel.textColor = RYColorForHex(@"#383838");
        [self addSubview:self.clarityLabel];
        
        self.closeButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [self.closeButton setImage:[UIImage imageNamed:@"clarity_close"] forState:UIControlStateNormal];
        [self.closeButton addTarget:self action:@selector(closeAction) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:self.closeButton];

        
        NSInteger version_id = [Tool safeIntForKey:@"version_id" defaultValue:4];
        self.index = [Tool safeIntForKey:@"videoBitrate" defaultValue:version_id==18?2200:1200];
        
        
        NSInteger selectedSegmentIndex = version_id == 18?2: 1;
        NSInteger segmentIndex = [Tool safeIntForKey:@"agoraRtcSizeWith" defaultValue:version_id==18?720:540];
        if (segmentIndex == 1080) {
            selectedSegmentIndex = 3;
        }else if(segmentIndex == 720)
        {
            selectedSegmentIndex = 2;
        }else if(segmentIndex == 540)
        {
            selectedSegmentIndex = 1;
        }else{
            selectedSegmentIndex = 0;
        }
        
        // 创建 UISegmentedControl
        self.segmentedControl = [[UISegmentedControl alloc] initWithItems:@[@"流畅",@"标清", @"高清", @"超清"]];
        self.segmentedControl.selectedSegmentIndex = selectedSegmentIndex;
        self.segmentedControl.layer.borderColor = RYColorForHex(@"#204DFF").CGColor;
        self.segmentedControl.layer.borderWidth = 1.0;
        [self.segmentedControl addTarget:self action:@selector(segmentedControlValueChanged:) forControlEvents:UIControlEventValueChanged];
        if (@available(iOS 13.0, *)) {
            self.segmentedControl.selectedSegmentTintColor = [UIColor colorWithRed:222/255.0 green:232/255.0 blue:255/255.0 alpha:1.0]; // #DEE8FF
        }
        // 设置未选中状态的背景色（白色）
        [self.segmentedControl setBackgroundImage:[self imageWithColor:[UIColor whiteColor]]
                                       forState:UIControlStateNormal
                                     barMetrics:UIBarMetricsDefault];

        // 3. 设置选中状态背景色（#DEE8FF）
        UIColor *selectedColor = [UIColor colorWithRed:222.0/255.0 green:232.0/255.0 blue:255.0/255.0 alpha:1.0];
        // 设置选中状态的背景色（蓝色）
        [self.segmentedControl setBackgroundImage:[self imageWithColor:selectedColor]
                                       forState:UIControlStateSelected
                                     barMetrics:UIBarMetricsDefault];
        
        
        [self.segmentedControl setTitleTextAttributes:@{NSForegroundColorAttributeName: RYColorForHex(@"#808080")}
                                      forState:UIControlStateNormal];
        [self.segmentedControl setTitleTextAttributes:@{NSForegroundColorAttributeName: RYColorForHex(@"#204DFF")}
                                      forState:UIControlStateSelected];
        
        // 添加到视图中
        [self addSubview:self.segmentedControl];
        [self.segmentedControl mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(self).offset(18);
            make.right.mas_equalTo(self).offset(-16);
            make.top.mas_equalTo(self.clarityLabel.mas_bottom).offset(22);
            make.height.offset(40);

        }];
        
        
        
        
        [self.clarityLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(self).offset(15);
            make.top.mas_equalTo(self).offset(10);
        }];
        
        [self.closeButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.mas_equalTo(self).offset(-15);
            make.top.mas_equalTo(self).offset(15);
            make.size.mas_equalTo(CGSizeMake(14, 14));
        }];
        
        
        
        UILabel *hunBitrate = [[UILabel alloc] init];
        hunBitrate.text = @"400";
        hunBitrate.font = [UIFont systemFontOfSize:14];
        hunBitrate.textColor = RYColorForHex(@"#000000");
        [self addSubview:hunBitrate];
        
        UILabel *thdBitrate = [[UILabel alloc] init];
        thdBitrate.text = @"4000";
        thdBitrate.font = [UIFont systemFontOfSize:14];
        thdBitrate.textColor = RYColorForHex(@"#000000");
        [self addSubview:thdBitrate];
        
        
        self.bitrateLabel = [[UILabel alloc] init];
        self.bitrateLabel.text = @"码率（kbps）";
        self.bitrateLabel.font = [UIFont systemFontOfSize:14];
        self.bitrateLabel.textColor = RYColorForHex(@"#000000");
        [self addSubview:self.bitrateLabel];
        
        [self.bitrateLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(self).offset(16);
            make.top.mas_equalTo(self.segmentedControl.mas_bottom).offset(22);
        }];
        
        
        self.bitrateSlider = [[UISlider alloc] init];
        self.bitrateSlider.minimumValue = 400.0;
        self.bitrateSlider.maximumValue = 4000.0;
        self.bitrateSlider.value = self.index;
        [self.bitrateSlider addTarget:self action:@selector(makeUpSliderValueChanged:) forControlEvents:UIControlEventValueChanged];
        [self addSubview:self.bitrateSlider];
        
        
        
        [hunBitrate mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(self).offset(16);
            make.top.mas_equalTo(self.bitrateLabel.mas_bottom).offset(70);
        }];
        
        [thdBitrate mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.mas_equalTo(self).offset(-14);
            make.top.mas_equalTo(self.bitrateLabel.mas_bottom).offset(70);
        }];
        
        [self.bitrateSlider mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(hunBitrate.mas_right).offset(5);
            make.centerY.mas_equalTo(hunBitrate);
            make.right.mas_equalTo(thdBitrate.mas_left).offset(-5);
        }];
        
        
        self.sliderImage = [[UIImageView alloc] init];
        self.sliderImage.image = [UIImage imageNamed:@"slider_value"];
//        self.sliderImage.alpha = 0; // 默认隐藏
        [self addSubview:self.sliderImage];
        
        
        CGFloat screenWidth = [UIScreen mainScreen].bounds.size.width;
        CGFloat sliderWidth = screenWidth - 126;
        CGFloat ratio = (self.index - 400.0f) / (4000.0f - 400.0f); // 关键：使用 .0f 强制浮点运算
        CGFloat offset = sliderWidth * ratio;

        
        [self.sliderImage mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(self).offset(offset);
            make.top.mas_equalTo(self.bitrateLabel.mas_bottom).offset(20);
            make.size.mas_equalTo(CGSizeMake(120, 39));
        }];
        
        
        
        // 2. 创建浮动标签
        self.sliderValueLabel = [[UILabel alloc] init];
        self.sliderValueLabel.textAlignment = NSTextAlignmentCenter;
        self.sliderValueLabel.textColor = [UIColor whiteColor];
        self.sliderValueLabel.font = [UIFont systemFontOfSize:14];
        self.sliderValueLabel.text = [NSString stringWithFormat:@"当前码率：%ld",(long)self.index];
        [self.sliderImage addSubview:self.sliderValueLabel];
        
        [self.sliderValueLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.top.right.mas_equalTo(self.sliderImage);
            make.bottom.mas_equalTo(self.sliderImage.mas_bottom).offset(-9);
        }];
        
        
        // 创建背景视图
        UIView *containerView = [[UIView alloc] init];
        containerView.backgroundColor = RYColorForHex(@"#EDF3FF"); // 浅灰色背景
        containerView.layer.cornerRadius = 8.0; // 圆角
        containerView.clipsToBounds = YES;

        // 创建UILabel
        UILabel *tipLabel = [[UILabel alloc] init];
        tipLabel.textColor = RYColorForHex(@"#808080");
        tipLabel.font = [UIFont systemFontOfSize:14];
        tipLabel.numberOfLines = 0;
        // 创建NSMutableAttributedString
        NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc] initWithString:@"注意:\n"
                                                                                                  "1.清晰度档位越高、码率越高，直播的画质越好，但主播和观众均需更好的网络环境;\n"
                                                                                                  "2.若有较多的用户反馈卡顿，建议码率降1200kbps以下"];

        // 创建NSMutableParagraphStyle并设置行间距
        NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
        paragraphStyle.lineSpacing = 3; // 设置行间距为3像素
        paragraphStyle.alignment = NSTextAlignmentLeft; // 文本左对齐

        // 应用段落样式到整个字符串
        [attributedText addAttribute:NSParagraphStyleAttributeName
                               value:paragraphStyle
                               range:NSMakeRange(0, [attributedText length])];

        // 应用字体
        [attributedText addAttribute:NSFontAttributeName
                               value:tipLabel.font
                               range:NSMakeRange(0, [attributedText length])];

        // 应用文本颜色
        [attributedText addAttribute:NSForegroundColorAttributeName
                               value:tipLabel.textColor
                               range:NSMakeRange(0, [attributedText length])];

        // 设置富文本
        tipLabel.attributedText = attributedText;

        // 设置UILabel的约束（使用Auto Layout）
        [containerView addSubview:tipLabel];
       
        // 将容器视图添加到父视图
        [self addSubview:containerView];
        
        [containerView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(self).offset(16);
            make.right.mas_equalTo(self).offset(-14);
            make.top.mas_equalTo(self.bitrateSlider.mas_bottom).offset(20);
            make.height.offset(123);
        }];
        
        [tipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(containerView).insets(UIEdgeInsetsMake(10, 10, 10, 10));
        }];

    }
    return self;
}


// 辅助方法：生成纯色图片
- (UIImage *)imageWithColor:(UIColor *)color {
    CGRect rect = CGRectMake(0, 0, 1, 1);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, color.CGColor);
    CGContextFillRect(context, rect);
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

#pragma mark - 清晰度选项卡
- (void)segmentedControlValueChanged:(UISegmentedControl *)segmentedControl
{
    
    self.index = segmentedControl.selectedSegmentIndex;
    if (self.index == 0) {
        self.sliderValueLabel.text = @"800";
        self.bitrateSlider.value = 800;
    }else if (self.index == 1)
    {
        self.sliderValueLabel.text = @"1200";
        self.bitrateSlider.value = 1200;
    }
    else if (self.index == 2)
    {
        self.sliderValueLabel.text = @"2200";
        self.bitrateSlider.value = 2200;
    }else{
        self.sliderValueLabel.text = @"3000";
        self.bitrateSlider.value = 3000;
    }
    
    CGFloat screenWidth = [UIScreen mainScreen].bounds.size.width;
    CGFloat sliderWidth = screenWidth - 126;
    CGFloat ratio = (self.bitrateSlider.value - 400.0f) / (4000.0f - 400.0f); // 关键：使用 .0f 强制浮点运算
    CGFloat offset = sliderWidth * ratio;

    
    [self.sliderImage mas_updateConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self).offset(offset);
        make.top.mas_equalTo(self.bitrateLabel.mas_bottom).offset(20);
        make.size.mas_equalTo(CGSizeMake(120, 39));
    }];
    
    
    if ([self.delegate respondsToSelector:@selector(clarityButtonsAction:)]) {
        [self.delegate clarityButtonsAction:segmentedControl.selectedSegmentIndex];
    }
}

#pragma mark - 码率
- (void)makeUpSliderValueChanged:(UISlider *)slider
{
    
    // 计算最近的 200 的倍数
        float step = 200.0;
        float newValue = roundf(slider.value / step) * step;
        
        // 确保不超出范围
        newValue = MIN(MAX(newValue, slider.minimumValue), slider.maximumValue);
        
        // 更新滑块值
        slider.value = newValue;
    
    NSLog(@"当前值：%.0f", newValue);
    if ([self.delegate respondsToSelector:@selector(sliderChangeValue:)]) {
        [self.delegate sliderChangeValue:slider.value];
    }
    // 更新标签文本
        self.sliderValueLabel.text = [NSString stringWithFormat:@"当前码率：%.0f", slider.value];
        
        // 计算标签位置（跟随滑块 thumb）
        CGFloat thumbCenterX = slider.frame.origin.x + (slider.value / slider.maximumValue) * slider.frame.size.width-14;
        CGFloat labelY = slider.frame.origin.y - 25; // 显示在滑块上方
        
        self.sliderImage.center = CGPointMake(thumbCenterX, labelY);
        
//        // 显示标签（带动画）
//        [UIView animateWithDuration:0.2 animations:^{
//            self.sliderImage.alpha = 1;
//        }];
        
        // 滑动结束后隐藏标签
//        [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(hideSliderLabel) object:nil];
//        [self performSelector:@selector(hideSliderLabel) withObject:nil afterDelay:1.0];
}

// 5. 隐藏标签
//- (void)hideSliderLabel {
//    [UIView animateWithDuration:0.3 animations:^{
//        self.sliderImage.alpha = 0;
//    }];
//}
- (void)closeAction
{
    [self hideView];
}

-(void)showView
{
    LSTPopView *popView = [LSTPopView initWithCustomView:self
                                                popStyle:LSTPopStyleSmoothFromBottom
                                            dismissStyle:LSTDismissStyleSmoothToBottom];

    popView.hemStyle = LSTHemStyleBottom;
    popView.backgroundColor = [UIColor clearColor];
    popView.bgColor = [UIColor clearColor];
    LSTPopViewWK(popView)
    popView.popDuration = 0.5;
    popView.dismissDuration = 0.5;
    popView.isClickFeedback = YES;
    popView.rectCorners = UIRectCornerTopLeft | UIRectCornerTopRight;
    popView.cornerRadius = 15;
    popView.sweepStyle = LSTSweepStyleY_Positive;
    popView.dragStyle = LSTDragStyleNO;
    popView.sweepDismissStyle = LSTSweepDismissStyleSmooth;
    popView.bgClickBlock = ^{
        NSLog(@"点击了背景");
        [wk_popView dismiss];
    };
    self.popView = popView;

    [popView pop];
}

-(void)hideView;
{
    [self.popView dismiss];
}
-(void)dealloc
{
    NSLog(@"dealloc");
}
@end
